package cn.itcast.demo.web;

import cn.itcast.demo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author 虎哥
 */
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @GetMapping("sync")
    public User getUserSync(){
        log.info("sync查询开始。。。");
        User user = getUser();
        log.info("sync查询成功。。。");
        return user;
    }

    @GetMapping("async")
    public Mono<User> getUserAsync(){
        log.info("async 查询开始。。。");
        Mono<User> mono = Mono.fromSupplier(this::getUser);
        log.info("async 查询成功。。。");
        return mono;
    }
    
    @GetMapping("flux")
    public Flux<User> getUserFlux(){
        log.info("flux 查询开始。。。");
        // 构建flux
        Flux<User> flux = createUserFlux();
        log.info("flux 查询成功。。。");
        return flux;
    }

    @GetMapping(value = "stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<User> getUserFluxStream(){
        log.info("stream 查询开始。。。");
        // 构建flux
        Flux<User> flux = createUserFlux();
        log.info("stream 查询成功。。。");
        return flux;
    }


    private Flux<User> createUserFlux(){
        return Flux.interval(Duration.ofSeconds(1))
//                .take(3)
                .map(i -> User.of("user_" + i, 20 + i.intValue()));
    }


    // 生成user的方法，模拟调用service，然后查询数据库
    private User getUser(){
        try {
            // 模拟业务耗时1秒
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return User.of("Rose", 18);
    }
}
